import { defineStore } from 'pinia'
import { ref } from 'vue'

export interface Department {
  id: string
  name: string
  code: string
  type: '临床科室' | '医技科室' | '行政科室' | '后勤科室'
  level: '一级科室' | '二级科室' | '三级科室'
  parentId?: string
  parentName?: string
  director: {
    id: string
    name: string
    title: string
    phone: string
    email: string
  }
  viceDirectors: Array<{
    id: string
    name: string
    title: string
    phone: string
    email: string
  }>
  location: {
    building: string
    floor: string
    room: string
    description: string
  }
  contact: {
    phone: string
    extension: string
    email: string
    fax?: string
  }
  capacity: {
    beds: number
    doctors: number
    nurses: number
    currentPatients: number
  }
  services: string[]
  equipment: Array<{
    name: string
    model: string
    status: '正常' | '维修' | '停用'
    purchaseDate: string
    warrantyDate: string
  }>
  workingHours: {
    weekdays: {
      start: string
      end: string
    }
    weekends: {
      start: string
      end: string
    }
    holidays: boolean
  }
  budget: {
    annual: number
    used: number
    remaining: number
    categories: Array<{
      name: string
      allocated: number
      used: number
    }>
  }
  performance: {
    monthlyVisits: number
    satisfaction: number
    revenue: number
    costs: number
    profit: number
  }
  status: '正常运营' | '暂停服务' | '科室调整' | '筹建中'
  description: string
  foundedDate: string
  createdAt: string
  updatedAt: string
}

export interface DepartmentStaff {
  id: string
  departmentId: string
  departmentName: string
  employeeId: string
  employeeName: string
  position: string
  role: '科主任' | '副主任' | '主治医师' | '副主任医师' | '住院医师' | '护士长' | '护士' | '技师' | '行政人员'
  joinDate: string
  status: '在职' | '调离' | '离职'
}

export const useDepartmentStore = defineStore('department', () => {
  const departments = ref<Department[]>([
    {
      id: 'DEPT001',
      name: '内分泌科',
      code: 'ENDO',
      type: '临床科室',
      level: '二级科室',
      parentId: 'DEPT_INTERNAL',
      parentName: '内科',
      director: {
        id: 'D001',
        name: '王主任',
        title: '主任医师',
        phone: '13900139001',
        email: 'wang.director@hospital.com'
      },
      viceDirectors: [
        {
          id: 'D002',
          name: '李副主任',
          title: '副主任医师',
          phone: '13900139002',
          email: 'li.vice@hospital.com'
        }
      ],
      location: {
        building: '门诊楼',
        floor: '3楼',
        room: '301-320',
        description: '门诊楼3楼东侧'
      },
      contact: {
        phone: '010-12345678',
        extension: '3001',
        email: 'endo@hospital.com',
        fax: '010-12345679'
      },
      capacity: {
        beds: 30,
        doctors: 8,
        nurses: 12,
        currentPatients: 25
      },
      services: ['糖尿病诊治', '甲状腺疾病', '骨质疏松', '内分泌代谢病'],
      equipment: [
        {
          name: '血糖仪',
          model: 'BGM-001',
          status: '正常',
          purchaseDate: '2023-01-15',
          warrantyDate: '2026-01-14'
        },
        {
          name: '甲状腺超声',
          model: 'US-TH-002',
          status: '正常',
          purchaseDate: '2022-06-20',
          warrantyDate: '2025-06-19'
        }
      ],
      workingHours: {
        weekdays: {
          start: '08:00',
          end: '17:30'
        },
        weekends: {
          start: '08:00',
          end: '12:00'
        },
        holidays: false
      },
      budget: {
        annual: 2000000,
        used: 1200000,
        remaining: 800000,
        categories: [
          { name: '人员支出', allocated: 1000000, used: 600000 },
          { name: '设备采购', allocated: 500000, used: 300000 },
          { name: '药品耗材', allocated: 300000, used: 200000 },
          { name: '其他支出', allocated: 200000, used: 100000 }
        ]
      },
      performance: {
        monthlyVisits: 1250,
        satisfaction: 4.5,
        revenue: 800000,
        costs: 600000,
        profit: 200000
      },
      status: '正常运营',
      description: '专业从事内分泌代谢疾病的诊断、治疗和研究的临床科室',
      foundedDate: '1998-03-15',
      createdAt: '2024-01-15T10:00:00',
      updatedAt: '2024-01-20T15:30:00'
    }
  ])

  const departmentStaff = ref<DepartmentStaff[]>([
    {
      id: 'DS001',
      departmentId: 'DEPT001',
      departmentName: '内分泌科',
      employeeId: 'D001',
      employeeName: '王主任',
      position: '科主任',
      role: '科主任',
      joinDate: '1998-03-15',
      status: '在职'
    },
    {
      id: 'DS002',
      departmentId: 'DEPT001',
      departmentName: '内分泌科',
      employeeId: 'D002',
      employeeName: '李副主任',
      position: '副主任',
      role: '副主任',
      joinDate: '2005-08-20',
      status: '在职'
    }
  ])

  const currentDepartment = ref<Department | null>(null)
  const searchQuery = ref('')
  const filterType = ref('')
  const filterStatus = ref('')
  const loading = ref(false)

  // 获取科室列表
  const getDepartments = async (params?: any) => {
    loading.value = true
    try {
      await new Promise(resolve => setTimeout(resolve, 500))
      return departments.value
    } finally {
      loading.value = false
    }
  }

  // 根据ID获取科室
  const getDepartmentById = (id: string) => {
    return departments.value.find(d => d.id === id)
  }

  // 根据类型获取科室
  const getDepartmentsByType = (type: string) => {
    return departments.value.filter(d => d.type === type)
  }

  // 获取顶级科室（一级科室）
  const getTopLevelDepartments = () => {
    return departments.value.filter(d => d.level === '一级科室')
  }

  // 获取子科室
  const getSubDepartments = (parentId: string) => {
    return departments.value.filter(d => d.parentId === parentId)
  }

  // 添加科室
  const addDepartment = async (department: Omit<Department, 'id' | 'createdAt' | 'updatedAt'>) => {
    loading.value = true
    try {
      const newDepartment: Department = {
        ...department,
        id: `DEPT${Date.now()}`,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString()
      }
      departments.value.unshift(newDepartment)
      return newDepartment
    } finally {
      loading.value = false
    }
  }

  // 更新科室信息
  const updateDepartment = async (id: string, updates: Partial<Department>) => {
    loading.value = true
    try {
      const index = departments.value.findIndex(d => d.id === id)
      if (index > -1) {
        departments.value[index] = {
          ...departments.value[index],
          ...updates,
          updatedAt: new Date().toISOString()
        }
        return departments.value[index]
      }
      throw new Error('科室不存在')
    } finally {
      loading.value = false
    }
  }

  // 删除科室
  const deleteDepartment = async (id: string) => {
    loading.value = true
    try {
      // 检查是否有子科室
      const hasSubDepartments = departments.value.some(d => d.parentId === id)
      if (hasSubDepartments) {
        throw new Error('该科室下还有子科室，无法删除')
      }

      // 检查是否有员工
      const hasStaff = departmentStaff.value.some(s => s.departmentId === id && s.status === '在职')
      if (hasStaff) {
        throw new Error('该科室下还有在职员工，无法删除')
      }

      const index = departments.value.findIndex(d => d.id === id)
      if (index > -1) {
        departments.value.splice(index, 1)
        return true
      }
      return false
    } finally {
      loading.value = false
    }
  }

  // 搜索科室
  const searchDepartments = (query: string) => {
    searchQuery.value = query
    if (!query) return departments.value
    
    return departments.value.filter(department => 
      department.name.includes(query) ||
      department.code.includes(query) ||
      department.director.name.includes(query) ||
      department.services.some(service => service.includes(query))
    )
  }

  // 按类型筛选
  const filterDepartmentsByType = (type: string) => {
    filterType.value = type
    if (!type) return departments.value
    
    return departments.value.filter(department => department.type === type)
  }

  // 按状态筛选
  const filterDepartmentsByStatus = (status: string) => {
    filterStatus.value = status
    if (!status) return departments.value
    
    return departments.value.filter(department => department.status === status)
  }

  // 员工管理
  const getDepartmentStaff = (departmentId: string) => {
    return departmentStaff.value.filter(s => s.departmentId === departmentId)
  }

  const addStaffToDepartment = async (staff: Omit<DepartmentStaff, 'id'>) => {
    loading.value = true
    try {
      const newStaff: DepartmentStaff = {
        ...staff,
        id: `DS${Date.now()}`
      }
      departmentStaff.value.unshift(newStaff)
      return newStaff
    } finally {
      loading.value = false
    }
  }

  const removeStaffFromDepartment = async (staffId: string) => {
    loading.value = true
    try {
      const index = departmentStaff.value.findIndex(s => s.id === staffId)
      if (index > -1) {
        departmentStaff.value[index].status = '调离'
        return true
      }
      return false
    } finally {
      loading.value = false
    }
  }

  const transferStaff = async (staffId: string, newDepartmentId: string, newDepartmentName: string) => {
    loading.value = true
    try {
      const staff = departmentStaff.value.find(s => s.id === staffId)
      if (staff) {
        staff.departmentId = newDepartmentId
        staff.departmentName = newDepartmentName
        staff.joinDate = new Date().toISOString().split('T')[0]
        return staff
      }
      throw new Error('员工不存在')
    } finally {
      loading.value = false
    }
  }

  // 设备管理
  const addEquipment = async (departmentId: string, equipment: Omit<Department['equipment'][0], 'purchaseDate'>) => {
    loading.value = true
    try {
      const department = departments.value.find(d => d.id === departmentId)
      if (!department) throw new Error('科室不存在')

      const newEquipment = {
        ...equipment,
        purchaseDate: new Date().toISOString().split('T')[0]
      }

      department.equipment.push(newEquipment)
      department.updatedAt = new Date().toISOString()
      return newEquipment
    } finally {
      loading.value = false
    }
  }

  const updateEquipmentStatus = async (departmentId: string, equipmentName: string, status: Department['equipment'][0]['status']) => {
    loading.value = true
    try {
      const department = departments.value.find(d => d.id === departmentId)
      if (!department) throw new Error('科室不存在')

      const equipment = department.equipment.find(e => e.name === equipmentName)
      if (equipment) {
        equipment.status = status
        department.updatedAt = new Date().toISOString()
        return equipment
      }
      throw new Error('设备不存在')
    } finally {
      loading.value = false
    }
  }

  // 预算管理
  const updateBudget = async (departmentId: string, budget: Department['budget']) => {
    loading.value = true
    try {
      const department = departments.value.find(d => d.id === departmentId)
      if (!department) throw new Error('科室不存在')

      department.budget = budget
      department.updatedAt = new Date().toISOString()
      return department
    } finally {
      loading.value = false
    }
  }

  const addBudgetExpense = async (departmentId: string, category: string, amount: number) => {
    loading.value = true
    try {
      const department = departments.value.find(d => d.id === departmentId)
      if (!department) throw new Error('科室不存在')

      const budgetCategory = department.budget.categories.find(c => c.name === category)
      if (budgetCategory) {
        if (budgetCategory.used + amount > budgetCategory.allocated) {
          throw new Error('支出超出预算')
        }
        budgetCategory.used += amount
        department.budget.used += amount
        department.budget.remaining -= amount
        department.updatedAt = new Date().toISOString()
        return department
      }
      throw new Error('预算类别不存在')
    } finally {
      loading.value = false
    }
  }

  // 获取科室树形结构
  const getDepartmentTree = () => {
    const topLevel = departments.value.filter(d => d.level === '一级科室')
    return topLevel.map(dept => ({
      ...dept,
      children: getSubDepartments(dept.id).map(subDept => ({
        ...subDept,
        children: getSubDepartments(subDept.id)
      }))
    }))
  }

  // 获取科室绩效排名
  const getDepartmentRanking = (metric: 'revenue' | 'visits' | 'satisfaction' | 'profit') => {
    return [...departments.value]
      .filter(d => d.status === '正常运营')
      .sort((a, b) => {
        if (metric === 'visits') {
          return b.performance.monthlyVisits - a.performance.monthlyVisits
        }
        return b.performance[metric] - a.performance[metric]
      })
  }

  // 获取设备统计
  const getEquipmentStats = () => {
    const allEquipment = departments.value.reduce((acc, dept) => {
      return acc.concat(dept.equipment)
    }, [] as Department['equipment'])

    const byStatus = allEquipment.reduce((acc, equipment) => {
      acc[equipment.status] = (acc[equipment.status] || 0) + 1
      return acc
    }, {} as Record<string, number>)

    const expiringSoon = allEquipment.filter(equipment => {
      const warrantyDate = new Date(equipment.warrantyDate)
      const threeMonthsFromNow = new Date()
      threeMonthsFromNow.setMonth(threeMonthsFromNow.getMonth() + 3)
      return warrantyDate <= threeMonthsFromNow
    })

    return {
      total: allEquipment.length,
      byStatus,
      expiringSoon: expiringSoon.length
    }
  }

  // 获取统计数据
  const getDepartmentStats = () => {
    const total = departments.value.length
    const active = departments.value.filter(d => d.status === '正常运营').length
    
    const byType = departments.value.reduce((acc, department) => {
      acc[department.type] = (acc[department.type] || 0) + 1
      return acc
    }, {} as Record<string, number>)

    const byStatus = departments.value.reduce((acc, department) => {
      acc[department.status] = (acc[department.status] || 0) + 1
      return acc
    }, {} as Record<string, number>)

    const totalBeds = departments.value.reduce((sum, dept) => sum + dept.capacity.beds, 0)
    const totalDoctors = departments.value.reduce((sum, dept) => sum + dept.capacity.doctors, 0)
    const totalNurses = departments.value.reduce((sum, dept) => sum + dept.capacity.nurses, 0)
    const totalPatients = departments.value.reduce((sum, dept) => sum + dept.capacity.currentPatients, 0)

    const totalRevenue = departments.value.reduce((sum, dept) => sum + dept.performance.revenue, 0)
    const totalCosts = departments.value.reduce((sum, dept) => sum + dept.performance.costs, 0)
    const totalProfit = totalRevenue - totalCosts

    const averageSatisfaction = departments.value.reduce((sum, dept) => sum + dept.performance.satisfaction, 0) / departments.value.length

    return {
      total,
      active,
      byType,
      byStatus,
      capacity: {
        totalBeds,
        totalDoctors,
        totalNurses,
        totalPatients,
        bedOccupancy: totalBeds > 0 ? (totalPatients / totalBeds * 100).toFixed(1) : '0'
      },
      financial: {
        totalRevenue,
        totalCosts,
        totalProfit,
        averageSatisfaction: averageSatisfaction.toFixed(1)
      }
    }
  }

  return {
    departments,
    departmentStaff,
    currentDepartment,
    searchQuery,
    filterType,
    filterStatus,
    loading,
    getDepartments,
    getDepartmentById,
    getDepartmentsByType,
    getTopLevelDepartments,
    getSubDepartments,
    addDepartment,
    updateDepartment,
    deleteDepartment,
    searchDepartments,
    filterDepartmentsByType,
    filterDepartmentsByStatus,
    getDepartmentStaff,
    addStaffToDepartment,
    removeStaffFromDepartment,
    transferStaff,
    addEquipment,
    updateEquipmentStatus,
    updateBudget,
    addBudgetExpense,
    getDepartmentTree,
    getDepartmentRanking,
    getEquipmentStats,
    getDepartmentStats
  }
}, {
  persist: {
    key: 'department-store',
    storage: localStorage,
    paths: ['departments', 'departmentStaff']
  }
})